
from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework import status

COMMON_ERRCODE = 999400
COMMON_ERRMESSAGE = '参数错误'


class CustomException(Exception):
    def __init__(self, code=COMMON_ERRCODE, detail=COMMON_ERRMESSAGE):
        super().__init__(self)
        self.code = code
        self.detail = detail


class CustomAPIException(APIException):
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = 'Invalid request'
    default_code = 'invalid_request'

    def __init__(self, detail=None, code=None, extra_data=None):
        super().__init__(detail=detail, code=code)
        self.extra_data = extra_data


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if isinstance(exc, CustomAPIException) and response is not None:
        response.data.update(exc.extra_data)
    return response
